"use strict";

import {
    //核心
    React, Enhance, Controller, Component, $, EventEmitter,
    //
    tools, classnames,
    // 组件
    Table, TabPage, Lang, Dialog, Tree,
    Form, Page, Upload, Icon, Grid,
    BoxWidget, Input, Button, Prompt, Link, Loaders, Editor, Resource, Directive, Lock
} from 'admin';

import FroalaEditor from 'FroalaEditor';

import valid from '../../validate/admin.json';

var {http, date, time} = tools;

/**
 *
 */
class ArticleController extends Controller {
    state = {
        status: [
            {title: 'switch-on', value: 1},
            {title: 'switch-off', value: 0}
        ],
        unit: [
            {title: 10201008, value: 10201008},
            {title: 10201009, value: 10201009},
        ],
        tableProps: {
            update: {},
            query: {},
            types: {
                label: function (data, options) {
                    if (data.val == 10201008)
                        return <span className={classnames('label bg-red')}><Lang lang={data.val}/></span>;
                    if (data.val == 10201009)
                        return <span className={classnames('label bg-yellow')}><Lang lang={data.val}/></span>
                }
            },
            onRowClick: this._handlerRowClick,
            buttons: {
                'edit': {
                    onClick: this._handlerEditDialog
                },
                upload: this._handlerCreateUpload,
                'delete': {
                    onClick: this._handlerDeleteDialog
                }
            },
            pk: 'id',
            fields: [
                {
                    order: 0,
                    name: 'id',
                    width: 50,
                    display: true
                },
                {
                    name: 'title',
                    order: 0,
                },
                {
                    name: 'img',
                    order: 0,
                    type: {
                        name: 'image',
                        options: {
                            baseUrl: window.RESOURCE_URL + 'article/'
                        }
                    },
                },
                {
                    name: 'url',
                    order: 0,
                },
                {
                    order: 0,
                    name: 'time',
                    type: {
                        name: 'datetime'
                    },
                    display: false
                },
            ]
        },
        selectRow: {},
        edit: {},
        saveButton: null,
        updateButton: null
    }

    /**
     * 在componentWillMount()在挂载发生之前立即被调用。
     */
    componentWillMount() {

    }

    /**
     *
     */
    constructor() {
        super();
    }

    render() {
        var {edit, selectRow} = this.state;
        var config = {
            height: 568,
            heightMax: 568,
            width: 320,
        }

        return (
            <Grid>
                <Grid col="12 12 12 12">
                    <BoxWidget
                        color="3"
                        buttons={[{icon:'add',title:'add',onClick:this._handlerAddDialog}]}
                        className="table-height scroll"
                    >
                        <Table ref="table" {...this.props} {...this.state.tableProps}/>
                    </BoxWidget>
                </Grid>

                {/*编辑器*/}
                <Grid col="12 12 6 6">
                    <BoxWidget
                        module={this.props.module}
                        controller={this.props.controller}
                        action="do_edit_content"
                        onSuccess={this._handlerEditContentSuccess}
                        elem={Form}
                        color="5"
                        title={this.state.selectRow.name}
                        buttons={[this.state.saveButton]}
                        className="edit-height"
                    >
                        <Input type="hidden" name="id" model={selectRow}/>
                        <Lock>
                            <FroalaEditor
                                ref="editor"
                                name="content"
                                config={config}
                            />
                        </Lock>
                    </BoxWidget>
                </Grid>


                {/*资源文件*/}
                <Grid col="12 12 6 6">
                    <BoxWidget color="0" title='' className="edit-height scroll">
                        <Resource/>
                    </BoxWidget>
                </Grid>

                {/*添加*/}
                <Directive name="Modal">
                    <Dialog
                        ref="addDialog"
                        elem={Form}
                        {...this.props}
                        action="do_add"
                        title={this._lang("add")}
                        onSuccess={this._handlerAddSuccess}
                        buttons={[{title:'submit',type:'submit'}]}
                    >
                        <Input type="text" name="title" message={this._lang("title")}/>
                        <Input type="textarea" rows="3" name="url" message={this._lang("url")}/>
                    </Dialog>
                </Directive>

                {/*编辑*/}
                <Directive name="Modal">
                    <Dialog
                        ref="editDialog"
                        elem={Form}
                        {...this.props}
                        action="do_edit"
                        title={this._lang("edit")}
                        onSuccess={this._handlerEditSuccess}
                        buttons={[{title:'submit',type:'submit'}]}
                    >
                        <Input type="hidden" name="id" value={edit.id}/>
                        <Input type="text" name="title" message={this._lang("title")} value={edit.title}/>
                        <Input type="textarea" rows="3" name="url" message={this._lang("url")} value={edit.url}/>
                    </Dialog>
                </Directive>
                <Directive name="Modal">
                    <Dialog
                        ref="deleteDialog"
                        elem={Form}
                        {...this.props}
                        action="do_delete"
                        title={this._lang('delete')}
                        rules={[]}
                        buttons={[{title: 'submit', type: 'submit'}]}
                        onSuccess={this._handlerDeleteSuccess.bind(this)}
                    >
                        <input type="hidden" name="id" value={edit.id}/>
                    </Dialog>
                </Directive>
            </Grid>
        );
    }

    renderTabPage() {
        var {module, controller} = this.props;

        //上传按钮
        var upload = this.state.selectRow.id ? (
            <Upload key="upload" url={`${window.SERVER_URL}/${module}/${controller}/do_upload`}
                    post={{id:this.state.selectRow.id}}
                    onSuccess={this._handlerUploadSuccess.bind(this,this.state.selectRow)}
            >
                <Button isLink={true}>
                    <Icon icon="upload" type="admin"/>
                    <Lang lang="upload"/>
                </Button>
            </Upload>
        ) : null;


        if (this.state.tableProps) {
            return (
                <Directive name="TabPage">
                    <TabPage.Page {...this.props}
                        close={true}
                        onClose={this._handlerPageClose.bind(this)}
                    >
                        <Grid>
                            <Grid col="12 12 12 12">
                                <BoxWidget
                                    color="3"
                                    buttons={[{icon:'add',title:'add',onClick:this._handlerAddDialog}]}
                                    className="table-height scroll"
                                >
                                    <Table ref="table" {...this.props} {...this.state.tableProps}/>
                                </BoxWidget>
                            </Grid>
                            <Grid col="12 12 6 6">
                                <BoxWidget
                                    module={this.props.module}
                                    controller={this.props.controller}
                                    action="do_edit_content"
                                    onSuccess={this._handlerEditContentSuccess}
                                    elem={Form}
                                    color="5"
                                    title={this.state.selectRow.name}
                                    buttons={this.state.selectRow.id?[{icon:'save',title:'save',type:'submit'}]:[]}
                                    className="edit-height"
                                >
                                    {this.renderEditor()}
                                </BoxWidget>
                            </Grid>
                            <Grid col="12 12 6 6">
                                <BoxWidget color="0" title='' className="edit-height scroll">
                                    <Resource/>
                                </BoxWidget>
                            </Grid>
                        </Grid>
                    </TabPage.Page>
                </Directive>
            )
        }
    }


    /**
     *
     * @param key
     * @param data
     * @param index
     * @returns {XML}
     * @private
     */
    _handlerCreateUpload(key, data, index) {
        return (
            <Upload
                url={window.SERVER_URL+"/scdc/upload/get_article"}
                onSuccess={this._uploadSuccess.bind(this)}
                post={{id:data.id}}
            ><Icon icon="upload" type="admin"/>
            </Upload>
        );
    }

    /**
     *
     * @private
     */
    _uploadSuccess(data) {
        if (data) {
            this.refs.table.update(data);
            this.setState({});
        }
    }


    /**
     *
     * @private
     */
    _handlerAddDialog() {
        this.refs.addDialog.show();
    }

    /**
     *
     * @param edit
     * @private
     */
    _handlerEditDialog(edit) {
        this.setState({edit}, function () {
            this.refs.editDialog.show();
        })
    }

    /**
     *
     * @param data
     * @private
     */
    _handlerAddSuccess(data) {
        if (data) {
            this.refs.table.refresh();
            this.refs.addDialog.hide();
            window.toast(<Lang lang="message.success.add"/>);
        } else {
            window.toast(<Lang lang="message.error.add"/>);
        }
    }


    /**
     *
     * @param update
     * @private
     */
    _handlerEditSuccess(data) {
        if (data) {
            this.refs.table.update(data);
            this.refs.editDialog.hide();
            window.toast(<Lang lang="message.success.edit"/>);
        } else {
            window.toast(<Lang lang="message.error.edit"/>);
        }
    }

    /**
     *
     * @param data
     * @private
     */
    _handlerUploadSuccess(row, data) {
        if (data) {
            row.images = data;
            this.state.selectRow = row;
            this.refs.table.update(row);
            window.toast(<Lang lang="message.success.upload"/>);
        }
    }

    /**
     *
     * @param row
     * @param data
     */
    _handlerRemoveSuccess(data) {
        if (data) {
            this.state.selectRow.images = data;
            this.refs.table.update(this.state.selectRow);
            window.toast(<Lang lang="message.success.upload"/>);
        }
    }

    /**
     * 表单查询
     * @param data
     * @returns {boolean}
     * @private
     */
    _handlerQuery(data) {
        this.refs.table.query(data);
        return false;
    }

    /**
     * 修改详情
     * @param data
     * @private
     */
    _handlerEditContentSuccess(data) {
        if (data) {
            window.toast(<Lang lang="message.success.edit"/>);
            this.refs.table.update(data);
        }
    }

    /**
     *
     * @param data
     * @private
     */
    _handlerRowClick(selectRow) {

        if (selectRow) {
            //上传按钮
            var uploadButton = (
                <Upload key="upload" url={`${window.SERVER_URL}/${this.props.module}/${this.props.controller}/do_upload`}
                        post={{id:this.state.selectRow.id}}
                        onSuccess={this._handlerUploadSuccess}
                >
                    <Button isLink={true}>
                        <Icon icon="upload" type="admin"/>
                        <Lang lang="upload"/>
                    </Button>
                </Upload>
            );

            var saveButton = {icon: 'save', title: 'save', type: 'submit'};

            this.setState({selectRow, uploadButton, saveButton}, function () {
                this.refs.editor.value = selectRow.content;
                // this.refs.editor.setContent(selectRow.content);
            });
        }
    }

    _handlerDeleteDialog(edit) {
        this.setState({edit}, (function () {
            this.refs.deleteDialog.show();
        }).bind(this));
    }

    _handlerDeleteSuccess(data) {
        if (data) {
            this.refs.table.refresh(data);
            this.refs.deleteDialog.hide();
            window.toast(<Lang lang="message.success.delete"/>);
        } else {
            window.toast(<Lang lang="message.error.delete"/>);
        }
    }

}

export default Enhance(ArticleController);